import {Row, Col, Input, Modal, Select, Menu, Button, Dropdown, Icon, Form, message, Spin} from 'antd';
// import Row from '../../../_antd1.11.2/Row';
// import Col from '../../../_antd1.11.2/Col';
// import Input from '../../../_antd1.11.2/Input';
// import Modal from '../../../_antd1.11.2/Modal';
// import Select from '../../../_antd1.11.2/Select';
const Option = Select.Option;
// import Menu from '../../../_antd1.11.2/menu';
const SubMenu = Menu.SubMenu;
const MenuItemGroup = Menu.ItemGroup;
// import Button from '../../../_antd1.11.2/Button';
// import Dropdown from '../../../_antd1.11.2/Dropdown';
// import Icon from '../../../_antd1.11.2/Icon';
// import Form from '../../../_antd1.11.2/Form'
const FormItem = Form.Item;
// import Spin from '../../../_antd1.11.2/Spin';
// import message from '../../../_antd1.11.2/message'
import cloneDeep from 'lodash/cloneDeep';
const  _  =  require('lodash');
import forEach from 'lodash/forEach';
import isEmpty from 'lodash/isEmpty'
import isArray from 'lodash/isArray';
import uniq from 'lodash/uniq'
import isEqual from 'lodash/isEqual';

import WeaInputSearch from '../../wea-input-search';
import WeaSearchBrowserBox from '../wea-search-browser-box';
import WeaAssociativeSearchMult from '../wea-associative-search-mult'
import WeaNewScroll from '../../wea-new-scroll';
import WeaTools from '../../wea-tools';
import WeaBrowserTree from '../wea-browser-single-tree/WeaBrowserTree';
import WeaSearchAdvance from '../../wea-search-advance';
import WeaBrowserTable from '../wea-browser-table';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import debounce from 'lodash/debounce'

const initialState = {
    showSearchAd:false,
    count: 0,
    visible: false,
    currentPage: 1,
    inputValue: '',
    searchPara: {},
    checkStrictly: false,
    browserConditions: [],
    showCheckedDatas: false,
    url: '',
    loadAllTreeData: false,
    displayType: '',
    loading: true,
}

class main extends React.Component {
    // static defaultProps = {
    //     mult:true,
    // }
    constructor(props) {
        super(props);
        const {dataUrl}=this.props;
        this.state = {
            visible: null,
            initialShowSearchAd:false,
            showSearchAd:false,
            isClearData: false,
            selectedData: {}, // 搜索按钮选中的数据
            searchKeys:[], // 搜索按钮选择的keys
            currentPage: 1,
            pageSize: props.pageSize || 20,
            count: 0,
            url: dataUrl,
            inputValue: '',
            searchPara: {},
            dataKey:'',
            inputId: '',
            inputName: '',
            inputTop: [],
            inputBottom: [],
            browserConditions: [],
            displayType: 'list', // list/tree
            contentType: 1, // 数据展示的类别
            quickSearch: props.quickSearchName || '',
            defaultExpandedKeys:[],
            hiddenIds:'',
            pagination: {},
            loading: true,
            hasPgTableData: {},
            treeData: [],
            checkedDatas:[],
            noPgTableData:{},
            checkStrictly: false,
            tableCheckedDatas: [],
            showCheckedDatas: false,
            loadAllTreeData: false,
        }
        // 自定义浏览按钮数据分割符特殊处理
        this.delimiter = props.idSeparator || ',';
    }
    componentDidMount() {
        // 默认显示数据
        if (!isEmpty(this.props.replaceDatas)) {
            this.replaceSearchValues(this.props.replaceDatas);

            const {dataUrl} = this.props;
            let url = dataUrl;
            this.getData(url, 1, true);
        }

    }
    componentWillReceiveProps(nextProps){
        if (this.props.value !== nextProps.value && isEmpty(nextProps.value)) {
            this.setState({isClearData: !this.state.isClearData});
            this.handleClear();
        }
        if (!isEqual(this.props.replaceDatas, nextProps.replaceDatas)) {
            this.replaceSearchValues(nextProps.replaceDatas);
        }
    }
    shouldComponentUpdate(...args) {
        return PureRenderMixin.shouldComponentUpdate.apply(this, args);
    }
    setLoading(bool) {
        this.setState({loading: bool});
    }
    formatInput(columns) {
        let inputId, inputName, inputTop = [], inputBottom = [];
        if (!isEmpty(columns)) {
            columns.forEach((item) => {
                if (item.isInputCol === 'true') {
                    inputName = item.dbField || item.dataIndex
                }
                if (item.isPrimarykey === 'true') {
                    inputId = item.dbField || item.dataIndex
                }
                if (item.hide === 'false') {
                    if (item.showType === '1') {
                        inputTop.push(item.dbField || item.dataIndex)
                    }
                    if (item.showType === '0') {
                        inputBottom.push(item.dbField || item.dataIndex)
                    }
                }
            })
        }
        if (!inputId) {
            inputId = 'requestid';
        }
        this.setState({
            inputName: inputName,
            inputId: inputId,
            inputTop: inputTop,
            inputBottom: inputBottom,
        });
    }
    formatUrl(url, params) {
        if (url && !isEmpty(params)) {
            url = `${url}${WeaTools.getFd(params)}`;
        }
        return url;
    }
    getData(url, currentPage, hasPagination = false, searchPara = {}, cb) {
        this.setLoading(true);
        let params = searchPara;
        const {pageSize, count} = this.state;
        url = url || this.state.url;
        currentPage = currentPage || this.state.currentPage;
        if (hasPagination) {
            params['min'] = (currentPage - 1) * pageSize + 1;
            params['max'] = currentPage * pageSize;
        }
        params['pageSize'] = pageSize;
        if(params['max'] && currentPage > 1) {
            if (params['max'] > count) params['max'] = count;
        }
        url = this.formatUrl(url, params);
        WeaTools.callApi(url,'GET').then(data=> {
            // if (data.type == 1){//分页table
            //     const dataKey = data.datas;
            //     this.setState({
            //         displayType: 'list',
            //         contentType: data.type,
            //     });
            // }
            if (data.type == 2){//不分页的table
                this.setState({
                    noPgTableData:{columns:data.columns,datas:data.datas},
                    displayType: 'table',
                    contentType: data.type,
                });
                this.formatInput(data.columns);
                cb && cb(url);
            }
            if (data.type == 3){//树
                let keysArr = [];
                const {topPrefix} = this.props;
                if (data.datas && data.datas.id) {
                    keysArr.push(`${topPrefix}0-${data.datas.id}`);
                }
                if (!isEmpty(data.datas)) {
                    this.setState({
                        displayType: 'tree',
                        contentType: data.type,
                        treeData: data.datas,
                        defaultExpandedKeys: keysArr,
                        loadAllTreeData: data.isLoadAll,
                    })
                }
            }
            if (data.type == 4){//自定义分页的list
                this.formatInput(data.columns);
                this.setState({
                    hasPgTableData: {columns:data.columns,datas:data.datas,count:data.total},
                    displayType: 'table',
                    contentType: data.type,
                })
                cb && cb(url);
            }
            this.setState({url});
            this.setLoading(false);
        }).then((result)=>{
        })
    }
    onSearchChange(v){
        const quickSearch = this.state.quickSearch;
        const {dataUrl} = this.props;
        const {setFieldsValue, validateFields} = this.props.form;
        let params = {};
        validateFields((errors, object) => {
            if (!!errors) {
                message.error('Errors in form!!!');
                return;
            }
            forEach(object, (value, key) => {
                if (value) params[key] = value;
            })
        });
        if (quickSearch) params[quickSearch] = v;
        this.getData(dataUrl, 1, true, params); // 搜索获取数据
        setFieldsValue(params); // 高级搜索数据联动
        this.setState({
            inputValue: v,
            showSearchAd: false,
            searchPara: params,
            showCheckedDatas: false,
        });
    }
    goSearch=(e)=>{
        const quickSearch = this.state.quickSearch;
        const {dataUrl} = this.props;
        e.preventDefault();
        const {validateFields} = this.props.form;
        let params = {};
        validateFields((errors, object) => {
            if (!!errors) {
                message.error('Errors in form!!!');
                return;
            }
            forEach(object, (value, key) => {
                if (value) params[key] = value;
            })
        });
        this.getData(dataUrl, 1, true, params); // 搜索获取数据
        this.setState({
            searchPara: params,
            showSearchAd:false,
            showCheckedDatas: false,
            inputValue: params[quickSearch] || ''
        });
    }
    showModal() {
        this.setState({visible: true});
    }
    setShowSearchAd(bool){
        const {showSearchAd}=this.state;
        this.setState({showSearchAd:bool, initialShowSearchAd:true})
    }
    onBrowerClick =(keys, selectedObj)=>{
        const {resetFields} = this.props.form;
        resetFields(); // 重置高级搜索
        const {dataUrl,conditionURL,hasAdvanceSerach} = this.props;
        if (hasAdvanceSerach) {
            WeaTools.callApi(conditionURL,'GET').then(data=>{
                let quickSearch = '';
                if (!isEmpty(data.conditions)) {
                    data.conditions.forEach((item)=> {
                        if (item.isQuickSearch) {
                            quickSearch = item.domkey[0];
                        }
                    })
                }
                const params = WeaTools.getParamsByConditions(data.conditions);
                if (!isEmpty(params)) {
                    // 初始条件更新在form中
                    const {setFieldsValue} = this.props.form;
                    setFieldsValue(params);
                }
                this.getData(dataUrl, 1, true, params, (url)=> {
                    if (!isEmpty(keys)) {
                        this.formatDatas(url, keys).then((data)=> {
                            this.setState({tableCheckedDatas: data.datas})
                        })
                    }
                });
                this.showModal();
                this.setState({browserConditions: data.conditions, inputValue: params[quickSearch] || '', quickSearch});
            });
        } else {
            this.getData(dataUrl, 1, true, {}, (url) => {
                if (!isEmpty(keys)) {
                    this.formatDatas(url, keys).then((data)=> {
                        this.setState({tableCheckedDatas: data.datas})
                    })
                }
            });
            this.showModal();
        }
        // reset selected data
        if (!isEmpty(keys)) {
            let datas = [];
            keys = uniq(keys);
            keys.forEach((k) => {
                datas.push(selectedObj[k]);
            })
            this.setState({checkedDatas: datas});
            // this.throwCurrentState(keys.join(this.delimiter), datas);
        } else {
            this.setState({
                checkedDatas: [],
                tableCheckedDatas: [],
            });
        }
    }
    formatDatas(url, keys) {
        keys = uniq(keys);
        url = url.replace(/&min=(\d)*/g, '').replace(/&max=(\d)*/g, '') + `&selectids=${keys.join(this.delimiter)}`;
        return WeaTools.callApi(url,'GET');
    }
    handleOk() {
        const {maxLength} = this.props;
        const {checkedDatas} = this.state;
        let values = [];
        let selectedData = {};
        !isEmpty(checkedDatas) && checkedDatas.forEach((d) => {
            values.push(d.id);
            selectedData[d.id] = d;
        })
        this.setState({
            visible: false,
            searchKeys: values,
            selectedData: selectedData
        });
        this.throwCurrentState(values.join(this.delimiter), checkedDatas);
        this.setState(initialState);//初始化浏览框
    }
    handleCancel() {
        this.setState(initialState);//初始化浏览框
        const {searchKeys} = this.state;
        this.setState({
            checkedDatas: [],
        });
        if (isEmpty(searchKeys)) this.setState({tableCheckedDatas: []});
    }
    handleClear() {
        this.setState({
            visible: false,
            isClearData: !this.state.isClearData,
            selectedData: {},
            checkedDatas: [],
            tableCheckedDatas: [],
            searchKeys: []
        });
        this.setState(initialState);//初始化浏览框
        this.throwCurrentState('');
    }
    set(datas) {
        this.replaceSearchValues(datas);
    }
    replaceSearchValues(datas = []) {
        let searchKeys = [], selectedData = {};
        datas.forEach((item) => {
            searchKeys.push(item.id);
            selectedData[item.id] = item;
        })
        this.setState({searchKeys:searchKeys, selectedData: selectedData});
        let ids = uniq(searchKeys).join(this.delimiter);
        this.setState({hiddenIds: ids});
        // this.throwCurrentState(searchkeys.join(this.delimiter), datas);
    }
    onBrowerChangeHandler(values, datas) {
        this.setState({searchKeys:values, selectedData: datas});
        const throwDatas = [];
        if (!isEmpty(values)) {
            values.forEach(v => {
                throwDatas.push(datas[v]);
            })
        }
        this.throwCurrentState(values.join(this.delimiter), throwDatas);
    }
    count(datas = [], rNum = false) {
        const {inputId} = this.state;
        let count = 0;
        let ids = [];
        datas.forEach((item)=> {
            ids.push(item[inputId] || item.id);
        })
        count += uniq(ids).length;
        if (rNum) return count;
        return count > 0 ? `(${count})` : '';
    }
    onTreeCheck(keys, datas) {
        const res = [];
        if (datas.length > 0) {
            datas.forEach(data => {
                res.push({
                    id: data.id,
                    name: data.name,
                })
            })
        }
        this.setState({checkedDatas: res});
    }
    onTableCheck(keys, datas) {
        const id = this.state.inputId;
        const name = this.state.inputName;
        const res = [];
        if (datas.length > 0) {
            datas.forEach(data => {
                res.push({
                    id: data[id] || data['id'] || '',
                    name: data[name + 'span'] || data[name] || data['name'] || '',
                })
            })
        }
        this.setState({checkedDatas: res, tableCheckedDatas: datas});
    }
    getSearchType() {
        let r = [];
        const {quickSearch} = this.state;
        const {hasAdvanceSerach} = this.props;
        if (quickSearch) {
            r.push('base');
        }
        if (hasAdvanceSerach) {
            r.push('advanced');
        }
        return r;
    }
    render() {
        let _this = this;
        const {contentHeight,hasAdvanceSerach,icon,dropMenuIcon,iconBgcolor,title,browerType,dataUrl,isaccount,min,max,virtualUrl,searchUrl,fieldName}=this.props;
        const {id,name,style,topPrefix,topIconUrl,otherPara,isMult,ifCheck,disabled,prefix,ifAsync,grouptree,resourcetree,value,type,mult,checkGroup,modalStyle} = this.props;
        const {loading, hasPgTableData,url,visible,activeKey,showSearchAd, inputValue, pageSize, count, currentPage} = this.state;
        const {displayType,selectedData,searchKeys, checkedDatas,checkStrictly, tableCheckedDatas, quickSearch, loadAllTreeData} = this.state;
        const {inputId, inputName, inputTop, inputBottom, contentType, treeData, defaultExpandedKeys, hiddenIds,showCheckedDatas} = this.state;
        let titleEle = (
            <Row>
                <Col span="22" style={{paddingLeft:20,lineHeight:'48px'}}>
                    <div className="wea-hr-muti-input-title">
                        {iconBgcolor ? <div className="wea-workflow-radio-icon-circle" style={{background:iconBgcolor ? iconBgcolor : ""}}><i className={icon}/></div>
                        : <span style={{verticalAlign:'middle',marginRight:10}}><i className={icon}/></span>}
                        <span style={{verticalAlign:'middle'}}>{title}</span>
                    </div>
                </Col>
            </Row>
        );
        let inputArr = (
            <WeaAssociativeSearchMult
                {...this.props}
                inputName={inputName}
                inputId={inputId}
                style={this.props.inputStyle}
                datas={selectedData}
                selectedValues={searchKeys}
                isClearData={this.state.isClearData}
                type={type}
                clickCallback={this.onBrowerClick}
                onChange={this.onBrowerChangeHandler.bind(this)}
            />
        );
        const buttons = [
                <Button key="submit" type="primary" size="large" onClick={this.handleOk.bind(this)} disabled={this.count(checkedDatas, true) == 0}>确 定{this.count(checkedDatas)}</Button>,
                <Button key="clear" type="ghost" size="large" onClick={this.handleClear.bind(this)}>清 除</Button>,
                <Button key="back" type="ghost" size="large" onClick={this.handleCancel.bind(this)}>取 消</Button>];

        const tableProps = {
        };
        let usePagination = false;
        if (contentType == 2) {
            tableProps.noPgTableData = this.state.noPgTableData;
        }
        if (contentType == 4) {
           tableProps.noSkHasPgTable = {
                contentType: 'hasPgTable',
                url: url,
                hasPgTableData: hasPgTableData,
            }
            usePagination = true;
        }
        const cHeight = (hasAdvanceSerach || quickSearch)? contentHeight - 46: contentHeight;
        return (
          <div>
           {inputArr}
           <input type="hidden" id={fieldName} name={fieldName} value={hiddenIds} />
           <Modal wrapClassName="wea-browser-single wea-browser-checkbox wea-browser-modal"
              title={titleEle}
              // style={{height:"579px"}}
              zIndex={this.props.zIndex}
              width={modalStyle.width}
              maskClosable={false}
              visible={visible}
              onCancel={this.handleCancel.bind(this)}
              footer={buttons}>
                <div className="prel">
                    {
                        (hasAdvanceSerach || quickSearch) && <WeaSearchAdvance
                            buttonsAd={this.getTabButtonsAd()}
                            searchType={this.getSearchType()}
                            searchsBaseValue={inputValue}
                            searchsAd={<Form horizontal>{this.getSearchs()}</Form>}
                            showSearchAd={showSearchAd}
                            setShowSearchAd={(bool)=>{this.setShowSearchAd(bool)}}
                            onSearchChange={(v)=>{this.setState({inputValue: v})}}
                            onSearch={this.onSearchChange.bind(this)}
                        />
                    }
                    {
                        !(hasAdvanceSerach || quickSearch) && displayType === 'table' &&
                        <div style={{height: 40}}>
                        </div>
                    }
                    <Spin spinning={loading}>
                        <div style={{minHeight: 440}}>
                            {displayType === 'table' &&
                                <WeaBrowserTable
                                    ref="tableList"
                                    {...tableProps}
                                    setLoading={this.setLoading.bind(this)}
                                    pageSize={this.state.pageSize}
                                    showCheckedDatas={showCheckedDatas}
                                    showCheckedDatasChange={ (bool) => this.setState({showCheckedDatas: bool})}
                                    checkedDatas={tableCheckedDatas}
                                    showCheck={true}
                                    useFixedHeader
                                    scroll
                                    weaSimple
                                    usePagination={usePagination}
                                    onChange={(p)=>{this.setState({pagination: p})}}
                                    pageinationSize="small"
                                    showTotal
                                    noOperate
                                    getSelection={(keys, datas) => this.onTableCheck(keys, datas)}
                                    getTableLoading={loading => this.setState({loading:loading})}
                                    contentHeight={cHeight}
                                />
                            }
                            {displayType === 'tree' &&
                                <WeaNewScroll height={cHeight}>
                                    <WeaBrowserTree
                                        clickNodeExpandChildren
                                        type={type}
                                        browserTree={false}
                                        checkable={true}
                                        topPrefix={topPrefix}
                                        dataUrl={dataUrl}
                                        checkedCb={this.onTreeCheck.bind(this)}
                                        checkedDatas={checkedDatas}
                                        isMult={true}
                                        icon={icon}
                                        treeData={treeData}
                                        defaultExpandedKeys={defaultExpandedKeys}
                                        checkStrictly={true}
                                        isLoadAll={loadAllTreeData}
                                            />
                                </WeaNewScroll>
                            }
                        </div>
                    </Spin>
                </div>
            </Modal>
          </div>
        );
    }
    throwCurrentState(ids, datas = []){
        const {inputName} = this.state;
        ids = uniq(ids.split(this.delimiter)).join(this.delimiter);
        this.setState({hiddenIds: ids});
        let names = [];
        datas.forEach((d) => {
            names.push(d[inputName + 'span'] || d[inputName] || d.name);
        });
        this.props.onChange && this.props.onChange(ids, names.join(this.delimiter), datas);
    }

    getSearchs(){
        const {browserConditions} = this.state;
        let items = [];
        !isEmpty(browserConditions)&& browserConditions.forEach( field => {
            items.push({
                com:(<FormItem
                    label={`${field.label}`}
                    labelCol={{span: `${field.labelcol}`}}
                    wrapperCol={{span: `${field.fieldcol}`}}>
                        {WeaTools.getComponent(field.conditionType, field.browserConditionParam, field.domkey,this.props, field)}
                    </FormItem>),
                colSpan: 2,
                hide: WeaTools.isComponentHide(field),
            });
        });
        return <WeaSearchBrowserBox  items={items} />
    }
    reset() {
        const {resetFields,setFieldsValue} = this.props.form;
        const {browserConditions} = this.state;
        const fields = {};
        browserConditions.forEach((c) => {
            let ct = c.conditionType.toUpperCase();
            let domkey = c.domkey[0];
            const filterKeys = [1, -1, '1', '-1'];
            if (ct === 'BROWSER') {
                if (!isEmpty(c.browserConditionParam) && filterKeys.indexOf(c.browserConditionParam.viewAttr) == -1) {
                    fields[domkey] = undefined;
                }
            } else {
                if (filterKeys.indexOf(c.viewAttr) == -1) {
                    fields[domkey] = undefined;
                }
            }
        })
        setFieldsValue(fields);
        this.setState({inputValue: ''});
    }
    getTabButtonsAd() {
        let _this = this;
        const {resetFields,validateFields} = this.props.form;
        return [
            <Button type="primary" onClick={(e)=>{this.goSearch(e)}}>搜索</Button>,
            <Button type="ghost" onClick={(e)=>{this.reset()}}>重置</Button>,
            <Button type="ghost" onClick={()=>{_this.setState({showSearchAd:false})}}>取消</Button>
        ]
    }
}

export default Form.create()(main);